﻿namespace WholeSlideImageLibrary.Formats.PhilipsTiff
{
    internal static class PhilipsTiffXmlMetadataValidator
    {
        public static bool Validate(PhilipsTiffXmlMetadata? metadata)
        {
            if (metadata is null)
            {
                return false;
            }

            if (metadata.ScanedImages is null)
            {
                return false;
            }

            foreach (PhilipsTiffXmlMetadataScanedImage image in metadata.ScanedImages)
            {
                PhilipsTiffXmlMetadataImageLevel[]? sequence = image.RepresentationSequence;
                if (sequence is null || sequence.Length == 0)
                {
                    return false;
                }

                bool zeroFound = false;
                for (int i = 0; i < sequence.Length; i++)
                {
                    PhilipsTiffXmlMetadataImageLevel? item = sequence[i];

                    if (item.Rows <= 0 || item.Columns <= 0)
                    {
                        return false;
                    }

                    for (int j = 0; j < i - 1; j++)
                    {
                        if (item.Number == sequence[j].Number)
                        {
                            return false;
                        }
                    }

                    if (item.Number == 0)
                    {
                        zeroFound = true;
                    }
                }

                if (!zeroFound)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
